<template>
  <div class="container-subject">
    <!-- 学科管理-学科 -->
    <el-card>
      <!-- 内容 -->
      <el-form label-width="80px" size="small" :inline="true" class="demo-form-inline">
        <el-form-item label="学科名称:">
          <el-input v-model="requestParameters.subjectName"></el-input>
        </el-form-item>
        <el-button @click="empty()">清除</el-button>
        <el-button type="primary" @click="handleSearch()">搜索</el-button>
        <el-button
          class="filter-item"
          style="float:right"
          type="success"
          @click="addDialogVisible = true"
          icon="el-icon-edit"
          title="新增学科"
        >新增学科</el-button>
        <!-- 点击新增按钮学科，弹出对话框--写在module-hmmm里面的components的响应文件里面 -->
      </el-form>
      <el-alert class="alert" :title="`数据一共${totalCount}条`" type="info" show-icon></el-alert>
      <!-- 学科列表表单区 -->
      <el-table style="width:100%" :data="tableData">
        <!-- 学科列表区每一项内容 -->
        <el-table-column width="48px" label="序号" type="index"></el-table-column>
        <el-table-column label="学科名称" width="208px" prop="subjectName"></el-table-column>
        <el-table-column label="创建者" width="205px" prop="username"></el-table-column>+
        <el-table-column label="创建日期" width="160px">
          <template slot-scope="scope">
            <!-- parseTimeByString--用字符串的方式解析时间 -->
            <span>{{ scope.row.addDate | parseTimeByString }}</span>
          </template>
        </el-table-column>
        <el-table-column label="前台是否显示" width="205px">
          <!-- 判断前台是否显示当prop-isdisplayByString唯一就是显示，否则不 -->
          <template slot-scope="scope">
            <span v-if="scope.row.isFrontDisplay == 1">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
        <el-table-column label="二级目录" width="205px" prop="twoLevelDirectory"></el-table-column>
        <el-table-column label="标签" width="205px" prop="tags"></el-table-column>
        <el-table-column label="题目数量" width="205px" prop="totals"></el-table-column>
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="$router.push('directorys')">学科分类</el-button>
            <el-button type="text" size="mini" plain @click="$router.push('tags')">学科标签</el-button>
            <el-button type="text" @click="showEditDialog(scope.row)" size="mini">修改</el-button>
            <el-button type="text" size="mini" plain @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- layout中sizes代表每页显示多少条（可以自定义），jumper用户可以手动输入跳到几页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="changePager"
        :current-page="Number(requestParameters.page)"
        :total="Number(totalCount)"
        :page-size="Number(requestParameters.pagesize)"
        :page-sizes="[5,10,20,50]"
        layout="total, prev, pager, next, sizes, jumper"
        style="float:right"
      ></el-pagination>
    </el-card>
    <!-- 新增学科对话框 -->
    <el-dialog title="新增学科" :visible.sync="addDialogVisible" width="400px">
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input v-model="addForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="addForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSub">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改学科对话框 -->
    <el-dialog title="修改学科" :visible.sync="editDialogVisible" width="400px">
      <!-- 表单区域 -->
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="修改学科" prop="subjectName">
          <el-input v-model="editForm.subjectName"></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="editForm.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSub">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, remove, add, update, detail } from "@/api/hmmm/subjects";
// 导入时间过滤器
import { parseTimeByString } from "@/filters/index.js";
// 导入新增学科对话框

export default {
  name: "subject-page",

  data() {
    return {
      // 学科列表
      sublist: [],

      // 总页数
      totalCount: 0,
      requestParameters: {
        // 当前页码
        page: 1,
        // 每一页显示多少条
        pagesize: 10,
        subjectID: null
      },

      // 控制新增学科对话框的显示与隐藏
      addDialogVisible: false,

      // 添加学科信息
      addForm: {
        // 学科名称
        subjectName: "",
        // 是否显示
        isFrontDisplay: true
      },
      // 添加学科验证
      addRules: {
        // 学科名称验证
        subjectName: [
          { required: true, message: "请输入学科名称", trigger: "blur" },
          { max: 10, message: "长度不能超过 10 个字符", trigger: "blur" }
        ]
      },
      // 修改对话框
      editDialogVisible: false,
      // 修改学科信息
      editForm: {
        // 学科名称
        subjectName: "",
        // 是否显示
        isFrontDisplay: true
      },
      // 修改学科id
      editId: 0,
      // 修改学科验证
      editRules: {
        // 学科名称验证
        subjectName: [
          { required: true, message: "请输入学科名称", trigger: "blur" },
          { max: 10, message: "长度不能超过 10 个字符", trigger: "blur" }
        ]
      },
      obj: {},
      input: "",
      value: "true",
      tableData: []
    };
  },
  // 刷新页面内容
  created() {
    this.getSubjectList();
  },

  methods: {
    // 添加学科
    addSub() {
      // 先进行预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请重新输入合法的学科名");
        }
        // 通过预验证
        const data = await subjectAdd(this.addForm);
        if (data.status !== 200) {
          return this.$message.error("添加新学科失败");
        }

        this.$message.success("添加新学科成功");
        // 关闭对话框
        this.addDialogVisible = false;
        this.getSubList();
      });
    },

    // 修改学科
    editSub() {
      // 先进行预验证
      this.$refs.editRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请重新输入合法的学科名");
        }

        const obj = {
          id: this.editId,
          subjectName: this.editForm.subjectName,
          isFrontDisplay: this.editForm.isFrontDisplay
        };
        const res = await subjectUpdate(obj);
        // console.log(res);
        if (res.status !== 200) {
          return this.$message.error("修改学科失败");
        }
        this.$message.success("修改学科成功");
        // 重新渲染
        this.getSubList();
        // 关闭对话框
        this.editDialogVisible = false;
      });
    },

    // 点击清除按钮，清除输入框里面的字符
    empty() {
      // 判断输入框里面是否有内容，有的话清空
      if (this.requestParameters.subjectName) {
        this.requestParameters.subjectName = "";
        this.getSubjectList();
      }
    },

    // 改变页面数据条数
    handleSizeChange(newSize) {
      this.requestParameters.page === 1;
      this.requestParameters.pagesize = newSize;
      this.getSubjectList(this.requestParameters);
    },
    // 进入某一页
    changePager(newPage) {
      this.requestParameters.page = newPage;
      this.getSubjectList();
    },

    // 新增学科，修改学科
    handleChange(id) {
      this.query();
      // this.$refs.editUser.dialogFormV();
      if (id === "add") {
        this.titleInfo.text = "新增学科"; // 给弹层传参
      } else {
        this.titleInfo.text = "修改"; // 给弹层传参
        this.hanldeEditForm(id);
      }
    },

    // 删除学科列表
    handleDelete(item) {
      // element-ui 确认框
      this.$confirm("此操作将永久删除该文章, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await this.$http.delete(`/subjects/${id}`);
            // 删除成功
            this.$message.success("删除成功");
            this.getSubjectList();
          } catch (e) {
            console.dir(e);
            // 删除失败
            this.$message.error("删除失败");
          }
        })
        .catch(() => {});
    },

    // 搜索学科列表
    handleSearch() {
      this.requestParameters.page = 1;
      this.getSubjectList();
    },
    // 修改学科对话框显示
    async showEditDialog(row) {
      // 先保存到editId中
      this.editId = row.id;
      this.editForm.subjectName = row.subjectName;
      this.editForm.isFrontDisplay = row.isFrontDisplay === 1 ? true : false;

      // 显示对话框
      this.editDialogVisible = true;
    },

    // 获取学科列表
    async getSubjectList() {
      try {
        const data = await list(this.requestParameters);
        console.log(data);
        this.tableData = data.data.items;
        this.totalCount = data.data.counts;
      } catch (err) {
        this.$message.error("获取列表失败");
      }
    }
  }
};
</script>

<style scoped >
.alert {
  margin-top: 20px;
  margin-bottom: 20px;
  padding: 8px 16px;
}
.el-dialog {
  box-sizing: border-box;
}
</style>
